package com.qfhd.soft.cjzcore.UI.MulitRecycle.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.RecyclerView;

import com.qfhd.soft.cjzcore.UI.Listener.CJOnlistListener;
import com.qfhd.soft.cjzcore.UI.MulitRecycle.decorate.Visitable;
import com.qfhd.soft.cjzcore.UI.MulitRecycle.factory.ItemTypeFactory;
import com.qfhd.soft.cjzcore.UI.MulitRecycle.viewholder.BaseViewHolder;

import java.util.List;

/**
 * Created by beifeng on 2017/2/17.
 */

public class MulitAdpter extends RecyclerView.Adapter<BaseViewHolder> {
  private ItemTypeFactory typeFactory;
  List<Visitable> mItems;
  private CJOnlistListener clickListener;
  /**
   * 构造函数
   */
  public MulitAdpter() {
    //  item工厂类 生产viewholder
    this.typeFactory = new ItemTypeFactory();
//    mItems=mData;
  }

  public void setList(List<Visitable> list){
    if(list != null){
      mItems = list;
      notifyDataSetChanged();
    }
  }

  public void addList(List<Visitable> newList){
    int startPosition   = mItems.size();
    int endPosition     = 0;
    if(newList != null){
      mItems.addAll(newList);
      endPosition     = mItems.size();
    }
    notifyItemRangeChanged(startPosition,endPosition);
  }

  public void setOnclickListener(CJOnlistListener listener){
    clickListener = listener;
  }

  @Override public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(viewType, parent,false);
    return typeFactory.createViewHolder(viewType, view);
  }

  @Override public void onBindViewHolder(BaseViewHolder holder, int position) {
    holder.bindViewData(mItems.get(position));
    if (holder != null) {
      holder.itemView.setOnClickListener(v -> {
        if (clickListener != null) {
          clickListener.onClick(holder.itemView, position);
        }
      });
    }
  }

  @Override public int getItemViewType(int position) {
    return mItems.get(position).type(typeFactory);
  }

  @Override public int getItemCount() {
    return (mItems != null ? mItems.size() : 0);
  }
}
